package observermall

import (
	"fmt"
	"math/rand"
	"time"
)

//  库存管理

type InventoryManager struct {
	products map[string]*Product
}

func NewInventoryManager() *InventoryManager {
	return &InventoryManager{
		products: make(map[string]*Product),
	}
}

// AddProduct 添加商品
func (m *InventoryManager) AddProduct(product *Product) {
	m.products[product.ID] = product
}

func (m *InventoryManager) SimulateChanges() {
	fmt.Println("\n===== 开始模拟商品变化 =====")

	// 获取所有产品ID
	productIDs := make([]string, 0, len(m.products))
	for id := range m.products {
		productIDs = append(productIDs, id)
	}

	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 5; i++ {
		// 随机选择一个产品
		productID := productIDs[rand.Intn(len(productIDs))]
		product := m.products[productID]

		// 随机选择一种变化类型
		changeType := rand.Intn(3)

		switch changeType {
		case 0: // 价格变化
			changePercent := (rand.Float64()*0.3 - 0.15) // -15% 到 +15%
			newPrice := product.Price * (1 + changePercent)
			product.SetPrice(newPrice)

		case 1: // 库存变化
			changeAmount := rand.Intn(30) - 10 // -10 到 +20
			newStock := product.Stock + changeAmount
			if newStock < 0 {
				newStock = 0
			}
			product.SetStock(newStock)

		case 2: // 新增型号
			variantNum := rand.Intn(3) + 1
			variantPrice := product.Price * (0.8 + rand.Float64()*0.4) // 80% 到 120% 的价格
			product.AddNewVariant(fmt.Sprintf("新型号-%d", variantNum), variantPrice)
		}

		// 随机间隔
		time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
	}
}
